import FS from 'fs-extra'
import { outputLog, getOneFieldWriteFile } from '../utils'
import { TsTransform } from './ts-build'
import { BabelTransform } from './babel-build'
import { TransformFileAsyncOptions } from '../interface'
import recursiveReaddirFiles, { IFileDirStat } from 'recursive-readdir-files'

/**获取文件*/
export const getFields = async (entry: string) => {
  const dirToFiles = await recursiveReaddirFiles(entry, {
    exclude: /(node_modules|tsconfig.json|build|dist|\.d\.ts|\.(test|spec)\.(ts|tsx|js|jsx))$/,
  })
  return dirToFiles
}

/**生成文件*/
export const transform = async (
  entry: string,
  options: TransformFileAsyncOptions,
) => {
  const { outDir = 'app', disableBabel = false } = options
  try {
    let newEnterFiles: IFileDirStat[] = []
    if (options.files) {
      newEnterFiles = getOneFieldWriteFile(options.files)
    } else {
      newEnterFiles = (await getFields(entry)) || []
    }
    newEnterFiles.forEach((item) => {
      if (item.ext && /ts|tsx/.test(item.ext)) {
        if (!disableBabel) {
          BabelTransform(item.path, entry, options)
        }
      } else {
        outputLog(item.path, item.path.replace(entry, outDir))
        FS.copySync(item.path, item.path.replace(entry, outDir))
      }
    })
    await TsTransform(
      newEnterFiles.map((item) => item.path),
      entry,
      options,
    )
  } catch (err) {
    throw err
  }
}
